package com.javasm.commons.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.List;
//跨域处理
@Configuration
@SuppressWarnings("unchecked")//List没有使用泛型， .@SuppressWarnings("unchecked") 隐藏所有的不安全的警告信息
public class CorsHandlerConfig {
    /**
     * CrosFilter注册到容器
     * web.xml通过滤器代理对象来引用CrosFilter
     */
    @Autowired
    private BootProperties bootProperties;

    @Bean
    public FilterRegistrationBean crosFilter(){
        //获取application.yml的配置信息
        BootProperties.CorsConfig corsConfig = bootProperties.getCorsConfig();

        //允许跨域地址 setAllowedOrigins
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(corsConfig.getOrigins());
        //跨域请求头 allowedHeaders
        List<String> allowedHeaders = corsConfig.getAllowedHeaders();
        if(allowedHeaders==null ||allowedHeaders.size()==0){
            configuration.addAllowedHeader("*");
        }else{
            configuration.setExposedHeaders(allowedHeaders);
        }
        //跨域请求方法 allowedMethods
        List<String> allowedMethods = corsConfig.getAllowedMethods();
        if(allowedMethods==null ||allowedMethods.size()==0){
            configuration.addAllowedMethod("*");
        }else{
            configuration.setAllowedMethods(allowedMethods);
        }

        //跨域是否允许携带cookie withCredentials
        Boolean withCredentials = corsConfig.getWithCredentials();
        configuration.setAllowCredentials(withCredentials);

        //跨域响应头 exposedHeaders
        List<String> exposedHeaders = corsConfig.getExposedHeaders();
        if(exposedHeaders!=null &&exposedHeaders.size()>0){
            configuration.setExposedHeaders(exposedHeaders);
        }
        // 跨域缓存时间 maxAge
        Long maxAge = corsConfig.getMaxAge();
        if(maxAge!=null){
            configuration.setMaxAge(maxAge);
        }

        //跨域路径 path（指定的路径进行跨域）
        String path = corsConfig.getPath();
        if(path==null)path="/**";

        //注册CORS跨域配置信息 registerCorsConfiguration
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration(path,configuration);

        //创建CORS过滤器对象 corsFilter
        CorsFilter corsFilter = new CorsFilter(configurationSource);
        //注册过滤器到tomcat容器中
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(corsFilter);
        filterRegistrationBean.setOrder(0);//设置跨域过滤器的优先级，跨域过滤器优先级应高于其他过滤器
        return filterRegistrationBean;
    }

}
